//
//  ViewController.m
//  edgeDemo
//
//  Created by dllo on 16/3/7.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "MainViewController.h"
#import "LeftView.h"
#import "WeatherView.h"

#import "MyCarLocatinViewController.h"


@interface MainViewController ()
<
UIGestureRecognizerDelegate,
LeftViewDelegate,
WeatherViewDelegate,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate
>
@property (nonatomic, strong) LeftView *leftView;
@property (nonatomic, strong) UIButton *tapCloseButton;
@property (nonatomic, strong) UIScreenEdgePanGestureRecognizer *panGesture;  //手势
@property (nonatomic, assign) BOOL openState;
@property (weak, nonatomic) IBOutlet UIButton *myCarButton;



@end

@implementation MainViewController

- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES animated:TRUE];
    
    NSString *libPath = [LIBRARY stringByAppendingString:@"/Caches"];
    NSString *path = [libPath stringByAppendingFormat:@"/bookmark.plist"];

    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
    if (array.count == 0) {
        [self.myCarButton setBackgroundImage:[UIImage imageNamed:@"btn_2"] forState:UIControlStateNormal];
    } else {
        [self.myCarButton setBackgroundImage:[UIImage imageWithData:array.lastObject] forState:UIControlStateNormal];
    }

    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.view.backgroundColor = [UIColor whiteColor];

    
    //初始化手势
    [self initPanGesture];
    
    WeatherView *weatherView = [[WeatherView alloc] initWithFrame:CGRectMake(8, 22, 398, 369)];
    weatherView.myDelegate = self;
    weatherView.httpArg = @"cityname=dalian&cityid=101070201";
    [weatherView GetData];
    [self.view addSubview:weatherView];
    
}

#pragma mark -- 左按钮执行方法
- (void)showLeftView{
    NSLog(@"左按钮被点击");
    [self prepareingLeftView];
    [self openingLeftController];
}



- (void)pushNextPage{
    
}


#pragma mark -- 初始化手势
- (void)initPanGesture{
    //初始化手势
    self.panGesture = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureEvent:)];
    self.panGesture.delegate = self;
    self.panGesture.edges = UIRectEdgeLeft;
    //给centerView添加手势
    [self.view addGestureRecognizer:self.panGesture];
    
    self.openState = NO;
}


#pragma mark -- 会捕捉到边缘手势 滑动就会一直执行
- (void)panGestureEvent:(UIPanGestureRecognizer*)panGesture {
    //获取手势的类别
    UIGestureRecognizerState state = panGesture.state;
    //该方法返回在横坐标上、纵坐标上拖动了多少
    CGPoint translation = [panGesture translationInView:self.leftView];
    //检测移动速度
    CGPoint velocity = [panGesture velocityInView:self.leftView];
    
    switch (state) {
            
            //识别器接收到触摸并识别出是它的手势时处于这个状态。响应方法将在下个循环步骤中被调用
        case UIGestureRecognizerStateBegan:
            NSLog(@"触摸开始%d", self.openState);
            
            [self prepareingLeftView];//调出菜单视图
            
            break;
            
            //识别器识别出手势之后开始变化执行
        case UIGestureRecognizerStateChanged:{
            static CGRect centerFrame;
            centerFrame = self.leftView.frame;
            centerFrame.origin.x += translation.x;
            if (centerFrame.origin.x < -414 - 10) {
                centerFrame.origin.x = -414;
            }
            if (centerFrame.origin.x > -100) {
                centerFrame.origin.x = -100;
            }
            self.leftView.frame = centerFrame;
        }
            break;
            
            //识别器在识别到作为当前手势结束信号的触摸时处于这个状态。响应方法将在下个循环步骤中被调用
            //并且 识别器将重置为possible状态
        case UIGestureRecognizerStateEnded:
        {
            NSLog(@"触摸结束%@ %d", self.leftView, self.openState);
            //滑动结果(划少了 划多了) 动画效果处理
            if (self.leftView.frame.origin.x > -394 && velocity.x > 0) {
                [self openingLeftController];
            } else {
                [self closeingLeftController];
            }
        }
            break;
            
        default:
            break;
    }
    [panGesture setTranslation:CGPointZero inView:self.view];
}


#pragma mark -- 调出菜单视图
- (void)prepareingLeftView{
    
    if (self.openState == 1) {
        return;
    }
    self.leftView = [[LeftView alloc] initWithFrame:CGRectMake(-414, 0, 414, 736)];
    self.leftView.myDelegate = self;
    [self showShadow:YES];  //阴影效果
    [self.view addSubview:self.leftView];
    
    
}


#pragma mark -- 打开菜单视图
- (void)openingLeftController {
    
    
    if (self.openState == 1) {
        return;
    }
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:10 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
        
        self.leftView.frame = CGRectMake(-100, 0, 414, 736);
        
    } completion:^(BOOL finished) {
        
        self.tapCloseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.tapCloseButton.frame = CGRectMake(314, 0, 100, 736);
        //        self.tapCloseButton.backgroundColor = [UIColor yellowColor];
        [self.tapCloseButton addTarget:self action:@selector(closeingLeftController) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.tapCloseButton];
        [self showShadow:YES];
        self.openState = YES;
        
    }];
    
}


#pragma mark -- 关闭菜单视图
- (void)closeingLeftController {
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:10 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
        
        self.leftView.frame = CGRectMake(-414, 0, 414, 736);
        
    } completion:^(BOOL finished) {
        
        [self.leftView removeFromSuperview];
        [self.tapCloseButton removeFromSuperview];
        self.openState = NO;
        
    }];
    [self showShadow:NO];
}


#pragma mark -- 阴影效果
- (void)showShadow:(BOOL)val {
    if (!self.leftView) return;
    
    self.leftView.layer.shadowOpacity = val ? 0.8f : 0.0f;
    if (val) {
        self.leftView.layer.cornerRadius = 4.0f;
        self.leftView.layer.shadowOffset = CGSizeZero;
        self.leftView.layer.shadowRadius = 4.0f;
        self.leftView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.view.bounds].CGPath;
    }
    
}

#pragma mark -- 爱车位置
- (IBAction)myLoveLocationClick:(id)sender {
    NSLog(@"爱车位置");
    NSString *libPath = [LIBRARY stringByAppendingString:@"/Caches"];
    NSString *path = [libPath stringByAppendingFormat:@"/bookmark.plist"];
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
    if (array.count == 0) {
        [self showImagePickController];
    } else {
        //进入相册页
        MyCarLocatinViewController *myCarVC = [[MyCarLocatinViewController alloc] init];
        [self.navigationController pushViewController:myCarVC animated:YES];
    }
    
}

#pragma mark --调取系统相册
-(void)showImagePickController
{
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    //  选择类型 （照片库模式， 相机模式， 相机胶片模式）
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;//代理
    imagePicker.allowsEditing = YES;//是否允许编辑
    // 模态，进入相册
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
    
}

#pragma mark --选中相片后会执行
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *libPath = [LIBRARY stringByAppendingString:@"/Caches"];
    NSString *path = [libPath stringByAppendingFormat:@"/bookmark.plist"];
    
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
    if (!array) {
        array = [NSMutableArray array];
    }

    //获取到选中的照片 并显示 并赋值给view的属性headImageView
    UIImage *image = [info valueForKey:@"UIImagePickerControllerOriginalImage"];
    NSData *imageData = UIImagePNGRepresentation(image);
    [array addObject:imageData];
    
    BOOL result = [array writeToFile:path atomically:YES];
    if (result) {
        NSLog(@"写入成功0%@", path);
    } else {
        NSLog(@"写入失败0%@", path);
    }
    
    
    // 通过模态返回
    [picker dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
}

#pragma mark --取消后会执行
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    // 通过模态消失
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
